package org.example.types.util;

/**
 * @author lxc18
 * @date 2025/4/8 11:04
 * @description RedisRateLimiter
 */
import lombok.RequiredArgsConstructor;
import org.example.types.common.RedisKeysPrefix;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
@RequiredArgsConstructor
public class RedisRateLimiter {


    @Resource
    private RedissonClient redissonClient;

    /**
     * 滑动窗口限流
     * @param key redis中的key
     * @param limit 最大QPS
     * @return 是否允许通过
     */
    public boolean tryAcquire(String key, int limit,int windowSize) {
        RScript script = redissonClient.getScript();
        // 使用 Redisson 执行 Lua 脚本
        // Pass arguments
        // 正确区分键和参数
        List<Object> keys = Collections.singletonList(key);
//        System.out.println("keys:"+keys+"limit:"+limit);
        Long result = script.eval(
                RScript.Mode.READ_WRITE,
                RedisKeysPrefix.LUA_SCRIPT_RATE_LIMIT,
                RScript.ReturnType.INTEGER,
                keys,
                limit,windowSize
                );

        return result != null && result == 1;
    }
}

